﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using LunwenYun.Portal.WebLogic;
using LunwenYun.Portal.Web.Models;
using LunwenYun.Infrastructure.Entities.Enum;
using LunwenYun.Tool.Framework;
using LunwenYun.Portal.Biz;

namespace LunwenYun.Portal.Web.Controllers
{
    [Compress]
    [ErrorHandle]
    public class AccountController : SiteBaseController
    {
        #region Login
        public ActionResult Login(string returnurl)
        {
            ViewBag.Return = returnurl;
            return View();
        }
        [HttpPost]
        public ActionResult Login(string username, string password, string validCode)
        {
            if (String.IsNullOrEmpty(username) ||
              String.IsNullOrEmpty(password) ||
              String.IsNullOrEmpty(validCode))
            {
                ViewBag.Error = "缺少必填项！";
                return View();
            }
            if (ValidateValidateCode(validCode))
            {
                var user = UserBiz.Login(username, password, false);
                if (user == null)
                {
                    ViewBag.UserName = username;
                    ViewBag.Error = "登陆失败，用户名或密码错误！";
                    return View();
                }
                else
                {
                    if (!user.IsActivate)
                    {
                        return Redirect("/account/beactivate?n=" + EncodeByBase64.Encode(username));
                    }
                    string backUrl = Request.Form["ReturnUrl"];
                    if (!String.IsNullOrEmpty(backUrl))
                    {
                        backUrl = Server.UrlDecode(backUrl);
                        backUrl = !backUrl.StartsWith("/") ? "/" + backUrl : backUrl;
                        return Redirect(backUrl);
                    }
                    return Redirect("/");
                }
            }
            ViewBag.UserName = username;
            ViewBag.Error = "验证码输入错误！";
            return View();
        }
        public ActionResult pleasenologin()
        {
            return View();
        }
        /// <summary>
        /// 验证验证码是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValidateValidateCode(string code)
        {
            bool result;

            string token = Request.Params["token"];
            if (token == null)
            {
                result = false;
            }
            else
            {
                token = Cryptogram.CommonEncrypt(token);
                //过虑加密后出现的非法字符
                token = token.Replace("/", "");
                token = token.Replace("+", "");
                token = token.Replace("=", "");
                token = token.Substring(0, 4).ToString();
                token = token.ToLower();
                //过虑0为O,I和1
                token = token.Replace("0", "o");
                token = token.Replace("1", "i");
                string validStr = code.ToLower();
                //o,0转换，i,1转换
                validStr = validStr.Replace("0", "o");
                validStr = validStr.Replace("1", "i");
                if (validStr != token)
                    result = false;
                else
                    result = true;
            }
            return result;
        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="t"></param>
        [HttpGet]
        public void validatetoken(string t)
        {
            const int width = 60, height = 25;
            Bitmap aBmp = new Bitmap(width, height);
            Graphics aGrph = Graphics.FromImage(aBmp);
            aGrph.FillRectangle(new SolidBrush(Color.FromArgb(68, 68, 68)), 0, 0, width, height);//255,153,0

            //string adPitch = ssolib.Cryptogram.CommonDecrypt(Request.QueryString["yyMM"].ToString());

            //为了解决浏览器后退，验证码不刷新的问题，对验证码的实现做了修改。 By Zhenli W.  2004-03-21
            string adPitch = Cryptogram.CommonEncrypt(t);

            adPitch = adPitch.Replace("/", "");
            adPitch = adPitch.Replace("+", "");
            adPitch = adPitch.Replace("=", "");

            adPitch = adPitch.Substring(0, 4);
            /*if(adPitch.Length < 4)
            {
                for(int i=0;i<4-adPitch.Length;i++)
                {
                    adPitch = adPitch + (new Random(i)).Next(0,9).ToString();
                }
            }*/
            //End Updated by Zhenli W.

            adPitch = adPitch.ToUpper();

            //过虑0为O,I和1
            adPitch = adPitch.Replace("0", "O");
            adPitch = adPitch.Replace("1", "I");
            new VerifyCodeImage().CreateImageOnPage(adPitch, 3, System.Web.HttpContext.Current);

        }
        public ActionResult beactivate(string n)
        {
            if (!String.IsNullOrEmpty(n))
            {
                try
                {
                    string u = EncodeByBase64.Decode(n);
                    if (!String.IsNullOrEmpty(u))
                    {
                        ViewBag.UserName = EncodeByBase64.Encode(u);
                        return View();
                    }
                }
                catch { }
            }
            return Redirect("/home/badrequest");
        }
        public ActionResult logout()
        {
            UserBiz.LogOut();
            return Redirect("/");
        }
        #endregion

        #region Register
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Register(RegisterModel model, string validCode)
        {
            if (!ValidateValidateCode(validCode))
            {
                ViewBag.Error = "验证码输入错误";
                return View();
            }
            var user = new LunwenYun.Infrastructure.Entities.Entity.User()
            {
                Area = (AreaCode)model.AreaCode,
                Email = model.UserName,
                Gender = (Gender)model.Gender,
                IsActivate = false,
                IsRefuse = false,
                Location = (Location)model.Location,
                NickName = model.NickName,
                Password = model.Password,
                Phone = model.Phone,
                Profession = (IndType)0,
                QQ = model.QQ,
                RcdDate = DateTime.Now,
                UserName = model.UserName.ToLower(),
                SystemRole = model.Role == 1 ? UserRole.Member : UserRole.PaperAgent,
                IsAuth = false,
                IsComplete = false,
                Industry = 0
            };
            if (UserBiz.Register(user) == null)
            {
                LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("用户：{0}注册失败。注册数据为：{1}",
                   user.UserName, user.ToJson()));
                ViewBag.Error = "用户名重复，请重新输入";
                return View();
            }
            return Redirect("/Account/registercomplete?u=" + Tool.Framework.EncodeByBase64.Encode(user.UserName));
        }
        public ActionResult RegisterComplete(string u)
        {
            ViewBag.Username = u;
            return View();
        }
        public ActionResult activation(string token)
        {
            var user = UserBiz.Activation(token);
            if (user != null)
            {
                ViewBag.User=user;
                ViewBag.Success = true;
                ViewBag.Message = "激活成功！";
            }
            else
            {
                ViewBag.Success = false;
                ViewBag.Message = "激活失败！";
            }
            return View();
        }
        public int resend(string u,int t=1)
        {
            string username = u;
            if (t == 1)
            {
                username = EncodeByBase64.Decode(username);
            }
            if (UserBiz.ReSendActiveMail(username) == null)
            {
                ViewBag.Error = "非注册用户名，请重新输入";
                return 0;
            }
            return 1;
        }
        /// <summary>
        /// 如果验证用户名为不存在返回 true
        ///              否则返回 false
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool usernameonly(string username)
        {
            var exists = UserBiz.UserNotExists(username);
            return exists;
        }
      
        #endregion

        #region ForgotPassword
        public ActionResult ForgotPassword()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ForgotPassword(string Username, string validCode)
        {
            ViewBag.Username = Username;
            if (!ValidateValidateCode(validCode))
            {
                ViewBag.Error = "验证码输入错误！";
                return View();
            }
            if (!UserBiz.ResendForgotPasswordMail(Username))
            {
                ViewBag.Error = "非注册用户，请查证！";
                return View();
            }
            return Redirect("/account/operationdone?t=0");
        }
        public ActionResult resetpassword(string token)
        {
            var user = UserBiz.CheckToken(token);
            if (user != null)
            {
                ViewBag.User = user.UserName;
                ViewBag.Nickname = user.NickName;
                ViewBag.U = Tool.Framework.AesAlgorithm.Encrypt(user.UserName);
                return View();
            }
            else
            {
                return Redirect("/account/operationdone?t=1");
            }
        }
        [HttpPost]
        public ActionResult setnewpassword(string u, string password)
        {
            string username = Tool.Framework.AesAlgorithm.Decrypt(u);
            var user = UserBiz.ChangePassword(username, password);
            if (user != null)
            {
                return Redirect("/account/operationdone?t=2");
            }
            return Redirect("/account/operationdone?t=3");
        }
        #endregion

        #region InfoModify
        public ActionResult MissPassword()
        {
            return View();
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="t">
        /// 0:重置密码，要求进入邮箱确认
        /// 1:重置密码验证失败
        /// 2:重置密码成功
        /// 3:重置密码失败
        /// 4:重发激活邮件成功
        /// </param>
        /// <returns></returns>
        public ActionResult OperationDone(int t = 0)
        {
            switch (t)
            {
                case 0:
                    ViewBag.HTitle = "操作成功";
                    ViewBag.H1 = "验证邮件已发送";
                    ViewBag.Content = "验证邮件已发送，请进入您的注册邮箱根据提示完成密码重置。";
                    break;
                case 1:
                    ViewBag.HTitle = "验证失败";
                    ViewBag.H1 = "令牌验证失败";
                    ViewBag.Content = "您的重置密码验证失败，请不要人为修改链接，请在申请后1日完成密码重置。";
                    break;
                case 2:
                    ViewBag.HTitle = "操作成功";
                    ViewBag.H1 = "修改密码成功";
                    ViewBag.Content = "修改密码成功，请妥善保管您的密码。";
                    break;
                case 3:
                    ViewBag.HTitle = "操作失败";
                    ViewBag.H1 = "修改密码失败";
                    ViewBag.Content = "修改密码失败失败，请稍后重试或联系管理员。";
                    break;
                case 4:
                    ViewBag.HTitle = "操作成功";
                    ViewBag.H1 = "激活邮件已重新发送";
                    ViewBag.Content = "激活邮件已重新发送至您的注册邮箱，请通过登录邮箱接收邮件完成激活操作。";
                    break;
            }
            return View();
        }
    }

}
